<script setup>
import {onMounted, ref} from "vue";
import {ElMessage} from 'element-plus';
import {logAPI} from '@/api/log/index.js';
import LogDetailDialog from "@/views/Log/LogDetailDialog.vue";
import { Search, Refresh, Download } from '@element-plus/icons-vue';

// 响应式数据
const state = ref({
  tableData: [],
  searchForm: {
    action: '',
    targetType: '',
    userId: ''
  },
  loading: false,
  pagination: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  dialog: {
    visible: false,
    currentLog: {}
  }
});

// API调用
const fetchData = async () => {
  try {
    state.value.loading = true;
    const res = await logAPI.getLogList({
      ...state.value.pagination,
      ...state.value.searchForm
    });

    state.value.tableData = res.data.records;
    state.value.pagination.total = res.data.totalRow;
  } catch (error) {
    ElMessage.error('获取日志列表失败: ' + error.message);
    console.error('API Error:', error);
  } finally {
    state.value.loading = false;
  }
};

// 分页处理
const handlePaginationChange = (type, val) => {
  if (type === 'size') {
    state.value.pagination.pageSize = val;
    state.value.pagination.pageNum = 1;
  } else {
    state.value.pagination.pageNum = val;
  }
  fetchData();
};

// 搜索重置
const resetSearch = () => {
  state.value.searchForm = {action: '', targetType: '', userId: ''};
  state.value.pagination.pageNum = 1;
  fetchData();
};

// 查看日志详情
const handleViewDetail = async (row) => {
  try {
    state.value.loading = true;
    const res = await logAPI.getLogDetail(row.id);
    state.value.dialog.currentLog = res;
    state.value.dialog.visible = true;
  } catch (error) {
    ElMessage.error('获取日志详情失败: ' + error.message);
  } finally {
    state.value.loading = false;
  }
};

// 导出日志
const handleExport = async () => {
  try {
    state.value.loading = true;
    const response = await logAPI.exportLog({
      ...state.value.searchForm
    });

    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'system_logs.xlsx');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    ElMessage.success('导出成功');
  } catch (error) {
    // 确保错误对象有 message 属性
    ElMessage.error('导出失败: ' + (error.message || '未知错误'));
    console.error('Export Error:', error);
  } finally {
    state.value.loading = false;
  }
};

onMounted(fetchData);
</script>

<template>
  <div class="log-management-container">
    <!-- 搜索卡片 -->
    <el-card shadow="hover" class="search-card">
      <div class="search-header">
        <h3>日志查询</h3>
        <div class="search-actions">
          <el-button
              type="primary"
              @click="fetchData"
              :loading="state.loading"
              :icon="Search"
          >
            查询
          </el-button>
          <el-button
              @click="resetSearch"
              :icon="Refresh"
          >
            重置
          </el-button>
          <el-button
              type="success"
              @click="handleExport"
              :loading="state.loading"
              :icon="Download"
          >
            导出数据
          </el-button>
        </div>
      </div>

      <el-form :model="state.searchForm" label-width="80px" class="search-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="操作类型">
              <el-input
                  v-model="state.searchForm.action"
                  placeholder="请输入操作类型"
                  clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="目标类型">
              <el-input
                  v-model="state.searchForm.targetType"
                  placeholder="请输入目标类型"
                  clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用户ID">
              <el-input
                  v-model="state.searchForm.userId"
                  placeholder="请输入用户ID"
                  clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 表格卡片 -->
    <el-card shadow="hover" class="table-card">
      <el-table
          :data="state.tableData"
          v-loading="state.loading"
          stripe
          border
          highlight-current-row
      >
        <el-table-column label="ID" prop="id" width="80" align="center"/>
        <el-table-column label="用户ID" prop="userId" width="100" align="center"/>
        <el-table-column label="操作类型" prop="action" width="180"/>
        <el-table-column label="目标类型" prop="targetType" width="120"/>
        <el-table-column label="IP地址" prop="ip" width="180"/>
        <el-table-column label="操作时间" prop="createdTime" width="180"/>
        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template #default="scope">
            <el-button
                type="primary"
                size="small"
                @click="handleViewDetail(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="state.pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            v-model:page-size="state.pagination.pageSize"
            v-model:current-page="state.pagination.pageNum"
            @size-change="val => handlePaginationChange('size', val)"
            @current-change="val => handlePaginationChange('page', val)"
        />
      </div>
    </el-card>

    <!-- 日志详情对话框 -->
    <LogDetailDialog
        v-model:visible="state.dialog.visible"
        :log-data="state.dialog.currentLog"
    />
  </div>
</template>

<style scoped>
.log-management-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-header h3 {
  margin: 0;
  color: #409EFF;
  font-size: 18px;
}

.search-form {
  margin-top: 10px;
}

.table-card {
  border-radius: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  font-size: 14px;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}
</style>